const {exec}=require('../db/mysql.js')
const xss = require('xss')

const getList=async (author,keyword)=>{//写的很妙啊,既可以查询author和keyword，没有时又可以返回所有数据
    let sql=`select * from blog where 1=1`;
    if(author){
        sql+=` and author='${author}'`;
    }else if(keyword){
        sql+=` and title like '%${keyword}%'`
    }
    sql+=` order by createtime desc`;
    return await exec(sql);
}

const getDetail=async (id)=>{
    let sql=`select * from blog where id=${id}`;
    return await exec(sql);
}

const newBlog=async (blogData={})=>{
    const title=xss(blogData.title);
    const content=xss(blogData.content);
    const author=xss(blogData.author);
    let createTime=Date.now();
    let sql=`insert into blog (title,content,createtime,author) 
     values ('${title}','${content}',${createTime},'${author}')`;
    return await exec(sql);
}

const updateBlog=async (id,blogData={})=>{
    const title=xss(blogData.title);
    const content=xss(blogData.content);
    let createTime=Date.now();
    let sql=`update blog set title='${title}',content='${content}',createtime=${createTime} 
     where id=${id}`;
    return await exec(sql);
}

const delBlog=async (id)=>{
    let sql=`delete from blog where id=${id}`;
    return await exec(sql);
}
module.exports={
    getList,
    getDetail,
    newBlog,
    updateBlog,
    delBlog
}